package com.bms.admin.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.bms.admin.auth.AuthCache;
import com.bms.admin.auth.UserRealm;
import com.bms.auth.ApiInterceptor;

@Configuration
public class WebConfig implements WebMvcConfigurer {

	@Autowired
	LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;

	@Bean
	public ApiInterceptor apiInterceptor(){
		ApiInterceptor apiInterceptor = new ApiInterceptor();
		apiInterceptor.setCache(redisCache());
		apiInterceptor.setUserRealm(userRealm());
		apiInterceptor.setTokenKey("bms");
		apiInterceptor.setDebug(true);
		return apiInterceptor;
	}
	
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    @Bean
    public AuthCache redisCache(){
        return new AuthCache();
    }
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		List<String> excludes = new ArrayList<>();
		excludes.add("/swagger-ui.html");
		excludes.add("/swagger-resources/**");
		excludes.add("/v2/api-docs");
		excludes.add("/webjars/springfox-swagger-ui/**");
		excludes.add("/login");
		excludes.add("/captcha.jpg");
		registry.addInterceptor(apiInterceptor()).addPathPatterns("/**").excludePathPatterns(excludes);
	}
	
	@Override
	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
		argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
	}

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**").allowedOrigins("*").allowCredentials(true)
				.allowedMethods("GET", "POST", "DELETE", "PUT","OPTIONS").maxAge(3600);
	}
	
	

}
